<template>
  <div>
    <div>
      <ele-page
        v-loading="loading"
        :formConfig="searchConfig"
        ref="eleTable"
        :operateList="operateList"
        @handleOperateEvent="handleOperateEvent"
        :column="column"
        :getList="getCapacitycodeHistoryList"
        uniqueId="mesBoxcodeprintHistoryTable"
      ></ele-page>
    </div>
    <ele-form-drawer class="dialog-pack" :isLoading="isLoading" v-model="formDataDialog" v-bind="formDescDialog" :request-fn="handleSubmit" :visible.sync="visible" :title="title"></ele-form-drawer>
    <!-- 补打模态框 -->
    <repairPrintModel ref="repairPrintModel" @refreshList="getListArr()"></repairPrintModel>
    <repairPrintTable ref="repairPrintTables"></repairPrintTable>
  </div>
</template>

<script>
import { operateList, searchConfig, importFormDescDialog, formDescDialog, rowConfig } from './config'

import { getCapacitycodeHistoryList, getPrinttypeList } from '@/api/print/mesCapacityCodePrintingRecord'

import { printTemplateInfoName } from '@/api/barcodeprint/mesBarcodeprintHistory'

import { uniqueKey } from '@/utils/judge.js'
import repairPrintTable from '@/views/print/mesCapacityCodePrinting/components/repairPrintTable.vue'
import repairPrintModel from '@/views/print/mesCapacityCodePrinting/components/repairPrintModel.vue'
import { popover } from '@/utils/judge'
import {
  selectListByConfigurationCode, //校验容量码补打是否需要审核
  reprintCapacitySelList,
  mesProdCapacitycodeReprint
} from '@/api/print/mesCapacityCode'
import { getDict } from '@/api/common'

export default {
  name: 'mesCapacityCodePrintingRecord',
  components: {
    repairPrintTable,
    repairPrintModel
  },
  data() {
    return {
      title: null,
      visible: false,
      isLoading: false,
      loading: false,
      formDataDialog: {},
      formDescDialog, //新增修改框
      searchConfig,
      operateList,
      getCapacitycodeHistoryList,
      isLoadingImport: false, // 导入数据loading
      importData: {}, //导入数据
      importVisible: false,
      importFormDescDialog, // 导入字段配置
      // 列表页字段的绑定配置
      column: [
        {
          type: 'selection'
        },
        {
          type: 'index',
          label: $i18n.t('common.order'),
          fixed: 'left',
          width: 60
        },

        {
          prop: 'barcode',
          label: $i18n.t('mesCapacityCodePrintingRecord.capacityCode'),
          fixed: 'left',
          minWidth: 450,
          showOverflowTooltip: true,
          render: (h, scope) => {
            return popover(scope.row.barcode, h)
          }
        },
        {
          prop: 'capacityType',
          label: $i18n.t('mesCapacityCodePrintingRecord.capacityType'),
          fixed: 'left',
          minWidth: 120,
          optionProp: {
            value: 'value',
            label: 'description'
          },
          option: async (data) => {
            const list = await getDict('template_type_capacitycode')
            return list.data.result
          }
        },
        {
          prop: 'planCode',
          label: $i18n.t('mesCapacityCodePrintingRecord.planCode'),
          minWidth: 180,
          showOverflowTooltip: true
        },
        {
          prop: 'orderCode',
          label: $i18n.t('mesCapacityCodePrintingRecord.orderCode'),
          minWidth: 240,
          showOverflowTooltip: true
        },
        {
          prop: 'prodCode',
          label: $i18n.t('mesCapacityCodePrintingRecord.prodCode'),
          minWidth: 180,
          showOverflowTooltip: true
        },
        {
          prop: 'prodName',
          label: $i18n.t('mesCapacityCodePrintingRecord.prodName'),
          minWidth: 280,
          showOverflowTooltip: true
        },
        {
          prop: 'seriesCode',
          label: $i18n.t('mesCapacityCodePrintingRecord.seriesCode'),
          minWidth: 180,
          showOverflowTooltip: true
        },
        {
          prop: 'seriesName',
          label: $i18n.t('mesCapacityCodePrintingRecord.seriesName'),
          minWidth: 180,
          showOverflowTooltip: true
        },

        {
          prop: 'barcodePrintTemp',
          label: $i18n.t('mesCapacityCodePrintingRecord.barcodePrintTemp'),
          minWidth: 170,
          showOverflowTooltip: true
        },
        {
          prop: 'printtime',
          label: $i18n.t('mesCapacityCodePrintingRecord.printTime'),
          width: 180
        },
        {
          prop: 'printtype',
          label: $i18n.t('mesCapacityCodePrintingRecord.printType'),
          minWidth: 120,
          optionProp: {
            value: 'value',
            label: 'description'
          },
          option: async (data) => {
            const list = await getPrinttypeList()
            return list.data.result
          }
        },
        {
          prop: 'userName',
          label: $i18n.t('mesCapacityCodePrintingRecord.printByName'),
          minWidth: 180,
          showOverflowTooltip: true
        },
        {
          prop: 'createByName',
          label: $i18n.t('common.createByName'),
          minWidth: 180,
          showOverflowTooltip: true
        },
        {
          prop: 'createTime',
          label: $i18n.t('common.createTime'),
          width: 180
        },
        {
          prop: 'updateByName',
          label: $i18n.t('common.updateByName'),
          minWidth: 180,
          showOverflowTooltip: true
        },
        {
          prop: 'updateTime',
          label: $i18n.t('common.updateTime'),
          width: 180
        },
        {
          prop: 'operate',
          label: $i18n.t('common.operation'),
          width: 120,
          fixed: 'right',
          render: (h, scope) => {
            return <ele-row-operation scope={scope} rowConfig={rowConfig} onRowOperate={this.rowOperate} />
          }
        }
      ]
    }
  },
  computed: {},
  methods: {
    //表格顶部按钮操作事件
    handleOperateEvent(data) {
      this.title = data.name
      const fnc = {
        add: () => {
          this.disableFields(false)
          this.formDataDialog = {}
          this.visible = true
        },
        deleteBatch: () => {
          this.$confirm($i18n.t('common.deleteBatch', { name: $i18n.t('mesCapacityCodePrintingRecord.name') }), $i18n.t('common.tip'), {
            confirmButtonText: $i18n.t('common.ok'),
            cancelButtonText: $i18n.t('common.cancel'),
            type: 'warning'
          }).then(() => {
            const ids = data.rows.map((val) => val.id).join(',')
            this.rowDel(ids)
          })
        },
        import: () => {
          this.importDialogData = {}
          this.importVisible = true
        },
        repairPrint: async () => {
          const workshopList = uniqueKey(data.rows, 'workshopCode')
          if (workshopList.length > 1) {
            this.$message.warning($i18n.t('mesCapacityCodePrintingRecord.sameWorkshop'))
            return
          }

          const { workshopCode } = data.rows[0]
          console.log('workshopCode', data.rows[0])
          let row = data.rows[0]
          let configData = {
            configurationCode: 'com_capacity_code_reviewed',
            levelType: '4',
            workshopCode: workshopCode
          }

          // 查询补打是否需要审核
          this.loading = true
          const res = await selectListByConfigurationCode(configData)
          const { result } = res.data
          this.loading = false
          //  true 需要审核  false 不需要审核
          let bool = false
          if (result && result.length) {
            if (result[0].value == '1') {
              bool = true
            }
          }
          // // 如果需要审核，跳转补打申请页面
          if (bool) {
            // 如果需要审核，只能选择1个条码
            if (data.rows.length > 1) {
              this.$message.warning($i18n.t('mesCapacityCodePrintingRecord.oneCode'))
              return
            }
            this.$refs.repairPrintTables.init({
              ...data.rows[0],
              isPrint: 0
            })
          } else {
            const tempList = uniqueKey(data.rows, 'barcodePrintTemp')
            if (tempList.length > 1) {
              this.$message.warning($i18n.t('mesCapacityCodePrintingRecord.limitTemp'))
              return
            }
            const temp = await printTemplateInfoName({
              templateName: tempList[0].barcodePrintTemp
            })
            let { orderCode, prodCode, capacityType, barcode, barcodePrintTemp, barcodePrintTempCode } = row
            const params = {
              orderCode: orderCode,
              prodCode: prodCode,
              capacityType: capacityType,
              startBarCode: barcode,
              endBarCode: barcode
            }
            const selData = await reprintCapacitySelList(params)
            // const barcodeInfo = {
            //   ...temp.data.result[0],
            //   values: selData.data.result
            // };
            // localStorage.splitPrint = JSON.stringify(barcodeInfo);
            // window.open(sys.publicPath+"splitPrint?type=12");

            let obj = {
              barcodePrintTempCode: barcodePrintTempCode,
              printType: 1,
              barcodePrintTemp: barcodePrintTemp,
              barCodeResult: selData.data.result
            }

            localStorage.splitPrint = JSON.stringify(obj)
            this.$router.push('/splitPrint')
          }
        }
      }
      fnc[data.handleName]()
    },
    //表格行操作事件
    rowOperate({ handleName, name, row }) {
      this.title = name
      const fnc = {
        edit: () => {
          this.disableFields(false)
          this.rowDetail(row)
          this.visible = true
        },
        detail: () => {
          this.disableFields(true)
          this.rowDetail(row)
          this.visible = true
        }
        // delete: () => {
        //   this.$confirm("此操作将删除该箱码打印历史记录表, 是否继续?", "提示", {
        //     confirmButtonText: "确定",
        //     cancelButtonText: "取消",
        //     type: "warning",
        //   }).then(() => {
        //     this.rowDel(row.id);
        //   });
        // },
      }
      fnc[handleName]()
    },
    doSubmit({ title, api, data }) {
      this.isLoading = true
      api(data)
        .then((res) => {
          const message = res.data.message
          this.$message.success(message || title)
          this.visible = false
          this.refresh()
        })
        .finally(() => {
          this.isLoading = false
        })
    },
    //弹框提交事件
    handleSubmit(data) {
      if (this.isLoading) return // 判断状态
      const params = this.formDataDialog.id ? { title: $i18n.t('common.editSuccess'), api: rowUpdate, data } : { title: $i18n.t('common.addSuccess'), api: rowCreate, data }
      this.doSubmit(params)
    },
    //删除
    rowDel(data) {
      this.loading = true
      rowDel(data)
        .then((res) => {
          const message = res.data.message
          this.$message.success(message || $i18n.t('common.deleteSuccess'))
          this.refresh()
        })
        .finally(() => {
          this.loading = false
        })
    },
    disableFields(flag) {
      this.formDescDialog.disabled = flag
      this.formDescDialog.isShowSubmitBtn = !flag
    },
    rowDetail(row) {
      this.formDataDialog = row
    },
    //刷新表格数据
    refresh(isReset = true) {
      this.$refs.eleTable.refresh(isReset)
    },
    //数据文件上传
    upLoadHandleChange(file) {
      this.$set(this.importData, 'file', file)
    },
    // 提交导入信息
    handleSubmitImport() {
      if (!this.importData.file) {
        this.$message.error($i18n.t('common.uploadMsg'))
        return
      }
      const formData = new FormData()
      formData.append('file', this.importData.file.get('file'))
      this.isLoadingImport = true
      importData(formData)
        .then((res) => {
          this.$message.success($i18n.t('common.importSuccess'))
          this.isLoadingImport = false
          this.importVisible = false
          this.refresh()
        })
        .catch((error) => {
          console.log('错误', error)
          this.$set(this.importData, 'file', null)
        })
        .finally(() => {
          this.isLoadingImport = false
          this.$refs.uploadNoAuto.clearFiles()
        })
    },
    getListArr() {
      this.refresh(false)
    }
  }
}
</script>
